#include "http_server.h"
#include <QJsonDocument>
#include <QDebug>

namespace infrastructure {
namespace io {

HttpServer::HttpServer(QObject* parent)
    : QTcpServer(parent)
{
}

void HttpServer::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket* socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);

    connect(socket, &QTcpSocket::readyRead, this, &HttpServer::socketReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, &HttpServer::socketDisconnected);
}

void HttpServer::socketReadyRead()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        QByteArray requestData = socket->readAll();
        QString request = QString::fromUtf8(requestData);

        // 检查是否为POST请求
        if (request.startsWith("POST")) {
            if (receive_callback != nullptr) {
                receive_callback(socket, request);
            } else {
                processPostData(request);
            }
        }

        socket->close();
    }
}

void HttpServer::socketDisconnected()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        socket->deleteLater();
    }
}

void HttpServer::respondPost(QTcpSocket* socket, const QJsonObject& jsonObj)
{
    QString response = "HTTP/1.1 200 OK\r\n"
                       "Content-Type: application/json\r\n"
                       "\r\n";

    QJsonDocument doc(jsonObj);
    QString strRet = QString(doc.toJson(QJsonDocument::Indented));
    response.append(strRet);

    socket->write(response.toUtf8());
    socket->flush();
    socket->waitForBytesWritten();
}

void HttpServer::processPostData(const QString& postData)
{
    // 默认处理 - 仅输出
    qDebug() << "POST data received:" << postData;

    QJsonDocument itemDoc = QJsonDocument::fromJson(postData.toLocal8Bit().data());
    QJsonObject rootObject = itemDoc.object();

    QString res = rootObject.value("res").toString();
    QString action = rootObject.value("action").toString();
    QString rid = rootObject.value("rid").toString();
}

} // namespace io
} // namespace infrastructure
